// import { createStore, applyMiddleware, compose, combineReducers } from "redux"
import { createStore, compose, combineReducers } from "redux"
// import thunk from "redux-thunk"
// import reducer from "./reducer"
import counterReducer from "./counter"
import homeReducer from "./home"
import userReducer from "./user"
import { thunk, log, applyMiddleware } from "./middleware"
// 正常情况下 store.dispatch(object)
// 想要派发函数 store.dispatch(function) 是不行的需要一个middleware redux-thunk

const reducer = combineReducers({
    counter: counterReducer,
    home: homeReducer,
    user: userReducer,
})

const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({ trace: true }) || compose
// const store = createStore(reducer, composeEnhancers(applyMiddleware(thunk)))
const store = createStore(reducer)

/* 
    实现打印日志中间件
*/

// function log(store) {
//     // 存储原有store的dispatch
//     const next = store.dispatch
//     function logAndDispatch(action) {
//         console.log("当前派发的action:", action)
//         // 通过原有的dispatch 来派发action
//         next(action)
//         console.log("派发action之后的改变：", store.getState())
//     }
//     // monkey patching：篡改现有的代码，对整体的执行逻辑进行修改
//     // 改变原有store的dispatch指向
//     store.dispatch = logAndDispatch
// }
// 调用log函数传入store
// log(store)
// 实现thunk效果
// function thunk(store) {
//     // 存储原有的dispatch
//     const next = store.dispatch
//     function dispatchThunk(action) {
//         if (typeof action === "function") {
//             action(store.dispatch, store.getState)
//         } else {
//             next(action)
//         }
//     }
//     store.dispatch = dispatchThunk
// }
// thunk(store)

applyMiddleware(store, log, thunk)

export default store
